#!/bin/bash

MAXLOAD="50"

case $1 in 
	status )
			case $2 in
				html )
					if ps -p $(cat mtm_db/pids/$3.pid) > /dev/null 
					then
						echo "<div style='display:inline;color:#00ff00;'>Running</div>"
					else
						echo "<div style='display:inline;color:#ff0000;'>Stopped</div>"
					fi
				;;
				
				return )
					if ps -p $(cat mtm_db/pids/$3.pid) > /dev/null 
					then
						echo "1"
					else
						echo "0"
					fi
				;;
			esac
			;;
	start-minetest )
		((./mtm_db/worlds/$2/bin/minetestserver --logfile mtm_db/users/$2.slog --config mtm_db/worlds/$2/minetest.conf --world `pwd`/mtm_db/worlds/$2/worlds/world) & jobs -p > mtm_db/pids/$2.pid) &

		sleep 10

		./setcpulimit $(cat mtm_db/pids/$2.pid) $MAXLOAD > /dev/null &

        mkdir -p mtm_db/worlds/$2/worlds/world/worldmods
		;;

	start-multicraft )
		((./mtm_db/worlds/$2/bin/multicraftserver --logfile mtm_db/users/$2.slog --config mtm_db/worlds/$2/minetest.conf --world `pwd`/mtm_db/worlds/$2/worlds/world) & jobs -p > mtm_db/pids/$2.pid) &

		sleep 20

		./setcpulimit $(cat mtm_db/pids/$2.pid) $MAXLOAD > /dev/null &

        mkdir -p mtm_db/worlds/$2/worlds/world/worldmods
		;;

	stopall )
		killall minetestserver
        killall multicraftserver
		;;
	stop )
		kill -15 $(cat mtm_db/pids/$2.pid)
        sleep 15
        if ps -p $(cat mtm_db/pids/$2.pid) > /dev/null 
        then
            kill -9 $(cat mtm_db/pids/$2.pid)
        fi
        ;;
    set-gamemode )
        echo "gameid = $3" >> mtm_db/worlds/$2/worlds/world/world.mt
        cp -a games/$3 mtm_db/worlds/$2/games/.
        ;;
	del )
        kill -9 $(cat mtm_db/pids/$2.pid)
        rm -r mtm_db/worlds/$2
        rm mtm_db/pids/$2.pid
        echo "false" > mtm_db/users/$2.pid.statuscode
        echo "<div style='display:inline;color:#ff0000;'>Stopped</div>" > mtm_db/users/$2.pid.status
        ;;
    del-debug ) rm mtm_db/worlds/$2/debug.txt;;
    mkmoddir ) mkdir mtm_db/worlds/$2/worlds/world/worldmods;;
	* )
 		echo "Usage: machine {start-mini|start-large|status|stop|stopall} {_|html|return} [vm id]";;
esac
